
import pyglet
import cocos
from cocos.director import director

import k_dialogs2 as dk
import dialog_node

class UIScene(cocos.scene.Scene):
    def __init__(self, app_model):
        super(UIScene,self).__init__()
        self.anchor = (0.0, 0.0)
        self.app_model = app_model
        #self.add(TestLayer())
        self.is_reenter = False
        self.dialog_layer = dialog_node.DialogLayer()
        self.add(self.dialog_layer)
        self.app_model.push_handlers(self.on_show_dialog,
                                     self.on_destroy_dialog,
                                     self.on_terminate_app,
                                     self.on_play_stage)
    def on_enter(self):
        print 'ui_scene on enter'
        super(UIScene,self).on_enter()
        if self.is_reenter:
            self.app_model.next_level()
        else:
            self.is_reenter = True
            self.app_model.start()
        
    def on_show_dialog(self, ev_data):
        cls_for_dialog = {
            'main_menu': dk.MainMenuDialog,
            'game_mode': dk.GameModeDialog,
            'player_settings': dk.PlayerSettingsDialog
            }
        dialog_name = ev_data.pop('dialog_name')
        dialog = cls_for_dialog[dialog_name](**ev_data)
        self.dialog_layer.add_dialog(dialog, name=dialog_name)

    def on_destroy_dialog(self, dialog_name):
        self.dialog_layer.remove_dialog(dialog_name)

    def on_terminate_app(self):
        pyglet.app.exit()

    def on_play_stage(self, controller_creation_info, world_creation_info):
        import level_scene
        scene = level_scene.get_game_scene(
                                controller_creation_info, world_creation_info)
        director.push(scene)
##        # never executed
##        print 'after play/push'
##        assert 1==0

# services
def get_ui_scene():
    import app_model
    app = app_model.AppModel()
    scene = UIScene(app)
    return scene

# publish services
import gg
gg.services["s_get_ui_scene"] = get_ui_scene




def test_ui_scene():
    director.init(width=640, height=480, resizable=True, 
                  do_not_scale=True)
    director.show_FPS = True
    pyglet.gl.glClearColor(.3, .3, .3, 1)
    import app_model
    app = app_model.AppModel()
    scene = UIScene(app)
    director.run(scene)

if __name__ == '__main__':
    test_ui_scene()
